<template>
  <div class="flex h-full">
    <a-card
      class="pt-2 mr-2 min-w-fit h-full w-[300px]"
      size="small"
      :body-style="{ height: '100%', padding: '0 8px', display: 'flex', flexDirection: 'column' }"
    >
      <SearchComb placeholder="姓名/助记码/卡号/手机号/身份证号" @search="queryList" />
      <BaseList :data-source="listDataSource" :loading="loading" class="flex-1 overflow-auto w-full">
        <template #renderItem="{ item }">
          <div class="py-2 px-3" :class="patientInfo.lsh === item.lsh ? 'active' : ''" @click="onSelectPatient(item)">
            <div class="flex justify-between mb-2">
              <div class="flex">
                <LabelValue class="text-primary text-base font-bold" :width="80" :value="item.brName" />
                <!-- <div class="w-[90px]">{{ item.brName }}</div> -->
                <span>{{ item.brXb }}</span>
                <span class="ml-2">{{ item.brAge }}</span>
              </div>
              <div class="text-primary">{{ item.sfsc }}</div>
            </div>
            <div class="flex justify-between">
              <LabelValue :width="40" :value="item.oprEyeType" />
              <div class="w-16 truncate">{{ item.ssys }}</div>
              <div>{{ item.oprDate }} {{ item.oprTime }}</div>
            </div>
          </div>
        </template>
      </BaseList>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <PatientInfoHeader :patient-info="patientInfo" @change="queryList">
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue class="ml-4" :label="isBJMSG ? '病历号' : '手术病案号'" :width="200" :value="patientInfo?.sfsc" />
            <LabelValue class="ml-4" label="手术医生" :width="210" :value="patientInfo?.ssys" tooltip />
            <LabelValue class="ml-4" label="手术时间" :width="210" :value="patientInfo?.oprDate && patientInfo?.oprDate + ' ' + patientInfo?.oprTime" tooltip />
            <LabelValue class="ml-4" label="麻醉方式" :width="140" :value="patientInfo?.anesthesiaMethodName" tooltip />
          </div>
          <div class="flex items-center">
            <LabelValue class="ml-4" label="眼别" :width="200" :value="patientInfo?.oprEyeType" tooltip />
            <LabelValue class="ml-4" label="右眼手术" :width="210" :value="patientInfo?.odmc" tooltip />
            <LabelValue class="ml-4" label="左眼手术" :width="210" :value="patientInfo?.osmc" tooltip />
            <LabelValue class="ml-4" label="咨询师" :width="140" :value="patientInfo?.zxysName" tooltip />
          </div>
        </div>
      </PatientInfoHeader>
      <a-card class="mt-2 w-full flex-1 overflow-auto" :class="{ 'disabled-style': !patientInfo?.lsh }">
        <a-form :model="formState" class="form-style-flex" :label-col="{ style: { width: '100px' } }">
          <div class="flex justify-between items-center w-full">
            <div class="flex-1 flex">
              <a-form-item :label="isBJMSG ? '病历号' : '手术病案号'" class="w-[380px] mr-2" v-bind="validateInfos.oprSn">
                <a-input v-model:value="formState.oprSn" :disabled="!isAllowModify" class="w-[80%]" :placeholder="isBJMSG ? '请生成病历号' : '请生成病案号'" />
                <a-button type="link" :disabled="!!formState?.oprSn || isAutoCode" class="w-[20%] p-0" @click="onClickMedical">生成</a-button>
              </a-form-item>
              <a-button type="primary" ghost class="ml-3" @click="onPrint">打印标签</a-button>
            </div>
            <div class="w-[200px] text-right pr-10 cursor-pointer" style="color: var(--primary-color)" @click="bookOpen = true">
              文书({{ formState.ophthDocument }})
            </div>
          </div>
          <a-divider class="!mt-2" />
          <a-form-item name="oprDate" class="w-1/5" label="手术日期" v-bind="validateInfos.oprDate">
            <a-date-picker v-model:value="formState.oprDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
          </a-form-item>
          <a-form-item name="oprTime" class="w-1/5 ml-5" label="手术时间" v-bind="validateInfos.oprTime">
            <a-time-picker v-model:value="formState.oprTime" format="HH:mm" value-format="HH:mm" />
          </a-form-item>
          <a-form-item name="oprEmpName" class="w-1/5 ml-5" label="手术医生" v-bind="validateInfos.oprEmpName">
            <SelectTable v-model:value="formState.oprEmpName" class="w-full" type="医生" @select="onSelect" />
          </a-form-item>
          <a-form-item class="w-1/5 ml-5" label="手术房间">
            <a-select v-model:value="formState.oprRoomId" placeholder="请选择" :options="surgicalRoomData" allow-clear />
          </a-form-item>
          <a-form-item class="w-1/5" label="一助">
            <SelectTable v-model:value="formState.assis1EmpName" allow-clear type="员工" placeholder="请输入" @select="onSelectNurse($event, 'assis1Emp')" />
          </a-form-item>
          <a-form-item class="w-1/5 ml-5" label="二助">
            <SelectTable v-model:value="formState.assis2EmpName" allow-clear type="员工" placeholder="请输入" @select="onSelectNurse($event, 'assis2Emp')" />
          </a-form-item>
          <a-form-item class="w-1/5 ml-5" label="巡回护士">
            <SelectTable v-model:value="formState.xunhEmpName" allow-clear type="职责护士" @select="onSelectNurse($event, 'xunhEmp')" />
          </a-form-item>
          <a-form-item class="w-1/5 ml-5" label="器械护士">
            <SelectTable v-model:value="formState.qixEmpName" allow-clear type="职责护士" @select="onSelectNurse($event, 'qixEmp')" />
          </a-form-item>
          <a-form-item class="w-1/5" label="洗眼护士">
            <SelectTable v-model:value="formState.xiyEmpName" allow-clear type="职责护士" @select="onSelectNurse($event, 'xiyEmp')" />
          </a-form-item>
          <a-form-item class="w-1/5 ml-5" label="病历护士">
            <SelectTable v-model:value="formState.binglEmpName" allow-clear type="职责护士" @select="onSelectNurse($event, 'binglEmp')" />
          </a-form-item>
          <a-form-item class="w-1/5 ml-5" label="刷手护士">
            <SelectTable v-model:value="formState.shuasEmpName" allow-clear type="职责护士" @select="onSelectNurse($event, 'shuasEmp')" />
          </a-form-item>
          <a-form-item class="w-1/5 ml-5" label="麻醉方式">
            <SelectItem v-model:value="formState.narcotismCode" select-first type="DT00012" placeholder="请选择" allow-clear />
          </a-form-item>
          <a-row class="w-full">
            <a-col :span="24" class="flex">
              <a-form-item class="w-1/6" label="右眼手术">
                <SelectTable v-model:value="formState.odmc" type="手术收费项目" allow-clear @select="onSelectOperation($event, 'odIcd9')" />
              </a-form-item>
              <a-form-item class="w-1/6" label="人工晶体">
                <a-input v-model:value="formState.odLens" placeholder="请输入" />
              </a-form-item>
              <a-form-item class="w-1/6" label="剩余度数">
                <a-input v-model:value="formState.odRemainingDegrees" placeholder="请输入" />
              </a-form-item>
              <a-form-item class="w-1/6" label="术前视力">
                <a-input v-model:value="formState.odPreOprVision" placeholder="请输入" />
              </a-form-item>
              <a-form-item class="w-1/6" label="负压环">
                <a-input v-model:value="formState.odPressure" placeholder="请输入" />
              </a-form-item>
              <a-form-item class="w-1/6" label="手术设备">
                <!-- :max-tag-count="1"
                mode="multiple" -->
                <SelectItem v-model:value="formState.listSurgicalOd" type="DT00279" placeholder="请选择" allow-clear :max-tag-count="1" mode="multiple" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row class="w-full">
            <a-col :span="24" class="flex">
              <a-form-item class="w-1/6" label="左眼手术">
                <SelectTable v-model:value="formState.osmc" type="手术收费项目" @select="onSelectOperation($event, 'osIcd9')" />
              </a-form-item>
              <a-form-item class="w-1/6" label="人工晶体">
                <a-input v-model:value="formState.osLens" placeholder="请输入" />
              </a-form-item>
              <a-form-item class="w-1/6" label="剩余度数">
                <a-input v-model:value="formState.osRemainingDegrees" placeholder="请输入" />
              </a-form-item>
              <a-form-item class="w-1/6" label="术前视力">
                <a-input v-model:value="formState.osPreOprVision" placeholder="请输入" />
              </a-form-item>
              <a-form-item class="w-1/6" label="负压环">
                <a-input v-model:value="formState.osPressure" placeholder="请输入" />
              </a-form-item>
              <a-form-item class="w-1/6" label="手术设备">
                <!-- :max-tag-count="1"
                mode="multiple" -->
                <SelectItem v-model:value="formState.listSurgicalOs" type="DT00279" placeholder="请选择" allow-clear :max-tag-count="1" mode="multiple" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="联合手术1" class="w-2/5">
            <SelectTable
              v-model:value="formState.jointOprCode1Name"
              type="手术"
              @select=";(formState.jointOprCode1 = $event.bh), (formState.jointOprCode1Name = $event.mc)"
            />
          </a-form-item>
          <a-form-item label="联合手术2" class="w-2/5">
            <SelectTable
              v-model:value="formState.jointOprCode2Name"
              type="手术"
              @select=";(formState.jointOprCode2 = $event.bh), (formState.jointOprCode2Name = $event.mc)"
            />
          </a-form-item>
          <a-form-item label="手术说明" class="w-full">
            <a-textarea v-model:value="formState.oprNotes" :rows="19" placeholder="请输入" />
          </a-form-item>
        </a-form>
        <div class="flex justify-end">
          <a-space>
            <a-button @click="getSurgicalInfo">重置</a-button>
            <a-button type="primary" :disabled="!isCompleted" @click="onSave">保存</a-button>
          </a-space>
        </div>
      </a-card>
    </div>
    <BookUpload v-model:open="bookOpen" :row-data="formState" @success="queryList" />
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import SearchComb from '@/components/SearchComb'
import PatientInfoHeader from '@/components/business/PatientInfoHeader'
import { post } from '@/utils/request'
import BaseList from '@/components/BaseList'
import SelectItem from '@/components/SelectItem'
import BookUpload from '../components/BookUpload.vue'

// import { getSystemConfig } from '@/utils/systemConfig'
const loading = ref(false)
const isAutoCode = ref(false)
const bookOpen = ref(false)
const listDataSource = ref([])
const nurseData = ref([])
const assistantData = ref([])
const surgicalRoomData = ref([])
const patientInfo = ref({})
const generate = ref({})
const formState = ref({
  oprSn: '',
  oprDate: dayjs().format('YYYY-MM-DD'),
  oprTime: dayjs().format('HH:mm'),
  oprEmpName: '',
  listSurgicalOd: [],
  listSurgicalOs: []
})
const params = ref({})
const rulesState = ref({
  oprSn: [{ required: true, message: '请点击生成手术备案号' }],
  oprTime: [{ required: true, message: '请选择手术时间' }],
  oprDate: [{ required: true, message: '请选择手术日期' }],
  oprEmpName: [{ required: true, message: '请选择手术医生' }]
})
const { validateInfos, isCompleted } = useForm(formState, rulesState)

//左侧数据
const queryList = async (param = {}) => {
  if (param?.endDate) params.value = param
  loading.value = true
  const { code, data, msg } = await post('/operation/opex/getOperationRecordList', {
    zjm: params.value?.searchKey,
    eddate: params.value?.endDate,
    stdate: params.value?.startDate,
    notStatus: '3'
  })
  loading.value = false
  if (code !== 0) return message.error(msg)
  listDataSource.value = data
  if (data && data.length > 0) {
    if (generate.value?.lsh) {
      const generateObj = data.filter((item) => item.lsh === generate.value.lsh)
      if (generateObj && generateObj.length > 0) {
        patientInfo.value = generateObj[0]
      } else {
        patientInfo.value = { ...data[0] }
      }
    } else {
      patientInfo.value = { ...data[0] }
    }
    onSelectPatient(patientInfo.value)
  } else {
    onReset()
  }
}

// 护士
const getNurseData = async () => {
  const { code, data } = await post('/operation/opex/getEmpInfoList', {
    emplbid: '2',
    yxzt: 0,
    pageNum: 1,
    pageSize: 9999
  })
  if (code !== 0) return
  nurseData.value = data.map((item) => {
    return {
      label: item.empName,
      value: item.empId
    }
  })
}
// 手术房间
const getOperationRoom = async () => {
  const { code, data, msg } = await post('/operation/opex/getBedMaintenanceDictInfoList', {
    bqbh: 'BQ00000161',
    bqmc: '手术病区',
    pageNum: 1,
    pageSize: 100
  })
  if (code !== 0) return message.error(msg)
  surgicalRoomData.value = data.map((item) => {
    return {
      label: item.cwh,
      value: item.id
    }
  })
}

// 一助 二助
const getUserAssistant = async () => {
  const { code, data } = await post('/operation/opex/getEmpInfoList', {
    yxzt: 0,
    pageNum: 1,
    pageSize: 9999
  })
  if (code !== 0) return
  assistantData.value = data.map((item) => {
    return {
      label: item.empName,
      value: item.empId
    }
  })
}
const onSelect = (select) => {
  formState.value.oprEmpName = select.empName
  formState.value.oprEmpId = select.empId
}
const onSelectNurse = (selected, key) => {
  formState.value[key + 'Id'] = selected.empId || ''
  formState.value[key + 'Name'] = selected.empName || ''
}
const onSelectOperation = (selected, key) => {
  formState.value[key] = selected.bh || ''
  if (key === 'odIcd9') {
    formState.value.odmc = selected.mc || ''
  } else {
    formState.value.osmc = selected.mc || ''
  }
}

const getSurgicalInfo = async () => {
  const res = await post('/operation/opex/getPostOperationRecord', { oprLsh: patientInfo.value.lsh || '' })
  if (res.code !== 0) return message.error(res.msg)
  formState.value = {
    ...formState.value,
    ...res.data
  }
  if (!formState.value.listSurgicalOd) {
    formState.value.listSurgicalOd = []
  }
  if (!formState.value.listSurgicalOs) {
    formState.value.listSurgicalOs = []
  }
}
// 点击生成病案号
const onClickMedical = async () => {
  // if (formState.value.oprSn) return message.error('手术病案号已存在')
  const res = await post('/operation/opex/doGenerateOperationId', {
    bqflag: 2,
    osOprBh: formState.value.osOprBh,
    odOprBh: formState.value.odOprBh,
    brId: patientInfo.value?.brId
  })
  if (res.code !== 0) return message.error(res.msg)
  formState.value.oprSn = res.data?.oprSn
}
const onSelectPatient = (row) => {
  formState.value = { ...row, oprEmpName: row.ssys }
  patientInfo.value = { ...row }
  generate.value = {}
  isAutoCode.value && onClickMedical()
  getSurgicalInfo()
}
// 清空
const onReset = () => {
  patientInfo.value = {}
}
const onSave = async () => {
  if (formState.value.listSurgicalOd && formState.value.listSurgicalOd.length) {
    formState.value.surgicalEquipmentOd = formState.value.listSurgicalOd.join(',')
  } else {
    formState.value.surgicalEquipmentOd = ''
  }
  if (formState.value.listSurgicalOs && formState.value.listSurgicalOs.length) {
    formState.value.surgicalEquipmentOs = formState.value.listSurgicalOs.join(',')
  } else {
    formState.value.surgicalEquipmentOs = ''
  }
  const { code, msg } = await post('/operation/opex/doSavePostOperationRecord', { ...formState.value, oprLsh: formState.value.lsh }, { loading: true })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  generate.value = formState.value
  queryList()
}
const isAllowModify = ref(false)
onMounted(() => {
  getNurseData()
  getOperationRoom()
  getUserAssistant()
  isAutoCode.value = getSystemConfig('OPERATION_NO_AUTO_GENERATE') === '1' // 病案号自动生成，0：手动，1：自动
  isAllowModify.value = getSystemConfig('OPERATION_NO_ALLOW_MODIFY') === '1' // '手术病案号允许手动修改', '0:不允许|1:允许'
})
const isBJMSG = getSystemConfig('GHDJYS') === '4' //是否北京茗视光
// 标签
const onPrint = async () => {
  const { code, msg, data } = await post('/outp/outPrint/getMedicalRecordLabelPrint', {
    brId: patientInfo.value.brId,
    type: 1,
    oprLsh: patientInfo.value.oprSn,
    lsh: patientInfo.value.lsh
  })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}
</script>

<style lang="less" scoped></style>
